package com.zzptc.mzb.shucheng1130;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.zzptc.mzb.shucheng1130.Bean.Book;
import com.zzptc.mzb.shucheng1130.Bean.User;

import org.litepal.LitePal;

public class LoginActivity extends AppCompatActivity {
private EditText usnedit,psdedit;
private Button loginbtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        getBook();
        getUser();
        initView();
        setListener();
    }

    private void getBook() {
        new Book(0,"剑来","烽火戏诸侯",R.drawable.jian1).save();
        new Book(0,"逆天邪神","火星引力",R.mipmap.a420).save();
        new Book(0,"帝霸","厌笔萧生",R.mipmap.a421).save();
        new Book(0,"万古神帝","飞天鱼",R.mipmap.a422).save();
        new Book(0,"执魔","我是墨水",R.mipmap.a523).save();
    }
    private void getUser() {
        new User(0,"1","1").save();
        new User(1,"2","2").save();
        new User(2,"3","3").save();

    }
    private void setListener() {
        loginbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String usn=usnedit.getText().toString().trim();
                String psd=psdedit.getText().toString().trim();
                User u=confirmUser(usn,psd);
                if(u==null){
                  //登录失败
                }else {
                    Intent it=new Intent(LoginActivity.this,MainActivity.class);
                    SharedPreferences sp=getSharedPreferences("userinfo",MODE_PRIVATE);
                    SharedPreferences.Editor editor=sp.edit();
                    editor.putInt("userid",u.getId());
                    editor.putString("username",u.getUsername());
                    editor.apply();
                    startActivity(it);
                }
            }
        });
    }
    private User confirmUser(String usn, String psd) {
        //判断User表中是否存在用户名
        for (User u: LitePal.findAll(User.class)){
            if (u.getUsername().equals(usn)&&u.getPassword().equals(psd)){
                return  u;
            }
        }
        return null;
    }

    private void initView() {
        usnedit=findViewById(R.id.usuedit);
        psdedit=findViewById(R.id.psdedit);
        loginbtn=findViewById(R.id.loginbtn);

    }
}
